package org.jwos.platform.util;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class MessageUtil {
	
	private static final String MESSAGE_FILE_NAME = "message";
	
	public static synchronized Map getMessageMap() {
		return getMessageMap(MessageUtil.class.getClassLoader(),Locale.getDefault());
	}
	
	public static synchronized Map getMessageMap(Locale locale) {
		return getMessageMap(MessageUtil.class.getClassLoader(),locale);
	}
	
	public static synchronized Map getMessageMap(ClassLoader classLoader) {		

		String resourceName = MESSAGE_FILE_NAME+".xml";
		String uri = getMessageUri(classLoader,resourceName);
		
		return getMessageMapByUri(uri);
	}
	
	public static synchronized Map getMessageMap(ClassLoader classLoader,Locale locale) {
		
		String resourceName = MESSAGE_FILE_NAME+"_"+locale.getLanguage()
				+ (locale.getCountry()!=null && locale.getCountry().length()>0 ? "_"+locale.getCountry() : "") + ".xml";
		String uri = getMessageUri(classLoader,resourceName);	
		if(uri==null) {
			resourceName = MESSAGE_FILE_NAME+".xml";
			uri = getMessageUri(classLoader,resourceName);
		}		
		
		return getMessageMapByUri(uri);
	}
	
	private static synchronized Map getMessageMapByUri(String uri) {		
		Map map = new HashMap();
		
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		try {
			builder = dbFactory.newDocumentBuilder();
			Document doc = builder.parse(uri);
			Element root = doc.getDocumentElement();
			NodeList list = root.getElementsByTagName("message");
			map = new HashMap();
			for (int i = 0; i < list.getLength(); i++) {
				Element element = (Element) list.item(i);
				map.put(element.getAttribute("key"), element.getAttribute("value"));
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return map;
	}
	
	private static synchronized String getMessageUri(ClassLoader classLoader,String resourceName) {
		String uri = null;
		
		URL url = classLoader.getResource(resourceName);
		if(url!=null) {
			uri = url.toString();
		}
		
		return uri;
	}	
	
	public static void main(String[] args) {
		System.out.println(getMessageMap(Locale.SIMPLIFIED_CHINESE));
		System.out.println(getMessageMap(Locale.JAPANESE));
		System.out.println(getMessageMap(Locale.ENGLISH));
	}
}
